$(document).ready(function () {

    function getPar(par) {
        var local_url = document.location.href;
        var getParam = local_url.indexOf(par + "=");
        if (getParam == -1) {
            return false;
        }
        var get_par = local_url.slice(par.length + getParam + 1);
        var nextPar = get_par.indexOf("&");
        if (nextPar != -1) {
            get_par = get_par.slice(0, nextPar);
        }
        return get_par;
    }

    //-------- add event listener

    chrome.runtime.onMessage.addListener(function (message) {
        if (message.event == 'editor.blog.save.result') {
            _result(message.data);
        }
        if (message.event == 'editor.category.get.result') {
            if (message.data.response) {
                _fillCategory(message.data.category);
            }
        }
        if (message.event == 'editor.blog.get.result') {
            if (message.data.blog) {
                _renderBlog(message.data.blog);
            }
        }
    });

    //-------- get category

    chrome.runtime.sendMessage({
        event: 'editor.category.get',
        data: null
    });

    //--------- get editable blog

    var id = getPar('id');

    if (id > 0) {
        chrome.runtime.sendMessage({
            event: 'editor.blog.get',
            data: {'id': id}
        })
    }

    function _renderBlog(blog) {
        $('#id').val(blog.id);
        $('#title').val(blog.title);
        $('#slug').val(blog.slug);
        richEditor.html($('<div/>').html(blog.content).text());
        $('#category').val(blog.categoryId);
        if(blog.isComment === '0'){
            $('#isComment').removeAttr('checked');
        }
    }

    //---------- render blog saving result

    function _result(result) {
        if (result.response) {
            $('#id').val(result.blog.id);
            $('#result').removeClass('error')
                .removeClass('loading')
                .text('保存 id = ' + result.blog.id);
        } else {
            $('#result').removeClass('loading')
                .addClass('error')
                .text(result.message);
        }
    }

    //--------- render category selection

    function _fillCategory(categories) {
        $.each(categories, function (i, c) {
            var str = '<option value="' + c.id + '">' + c.name + '</option>';
            $('#category').append(str);
        })
    }

    //---------- render rich text editor

    window.richEditor = KindEditor.create('#content', {
        width: $('#editor-main').width(),
        height: $(document).height() - 42,
        resizeType: 0,
        allowPreviewEmoticons: false,
        allowImageUpload: false,
        themeType: 'simple',
        shadowMode: false,
        pagebreakHtml: '<hr class="blog-break"/>',
        newlineTag: 'p',
        items: [
            'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
            'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
            'insertunorderedlist', '|', 'image', 'link', 'code', 'pagebreak', '|', 'source',
            'fullscreen', 'preview', 'about']
    });

    //------------- add form submit event

    function _validate() {
        var reg = /^[a-zA-Z]{1}[a-zA-Z0-9-]{1,100}$/;
        if (!reg.exec($('#slug').val())) {
            $('#result').addClass('error').text('缩略名无效');
            return false;
        }
        if ($('#content').val().indexOf('<hr class="blog-break" />') === -1) {
            $('#result').addClass('error').text('文章没有分割');
            return false;
        }
        return true;
    }

    $('#editor-wrapper').on('submit', function (e) {
        e.preventDefault();
        richEditor.sync();
        console.log(_validate());
        if (!_validate()) {
            return;
        }
        $('#result').removeClass('error').addClass('loading').text('');
        chrome.runtime.sendMessage({
            event: 'editor.blog.save',
            data: {
                formData: $('#editor-wrapper').serialize(),
                id: parseInt($('#id').val())
            }
        });
    });

});